﻿
-- ================================================
-- Remarks: Hard delete is required on specific rows
-- so check for delete type
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'Ivy_UserProfile_Delete')
	BEGIN
		DROP  Procedure  Ivy_UserProfile_Delete
	END
GO

CREATE PROCEDURE [Ivy_UserProfile_Delete]
-- =============================================
-- Author:		<Ali Balci>
-- Create date: <27/03/2011>
-- Description:	<Ivy_UserProfile_Delete>
-- =============================================
-- Add the parameters for the stored procedure here
	(
				@UserKey int,

				@ConcurrencyTimeStamp datetime  = NULL
	)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	-- Hard delete is required on specific rows so check for delete type
	DECLARE @CurrentRecordDeleteType int;
	SET @CurrentRecordDeleteType = (SELECT [Sys_DeleteType] FROM [UserProfile] WHERE [UserKey] = @UserKey);
	IF @CurrentRecordDeleteType = 1	
	BEGIN
		RAISERROR('Physical delete of this record is not allowed. Only soft delete is allowed', 11,1);
	END

	-- ConcurrencyTimeStamp is mandatory and it needs to check if any other user has changed the reord or not	
	IF @ConcurrencyTimeStamp = NULL
	BEGIN
		RAISERROR('Missing @ConcurrencyTimeStamp', 11,1);
	END
	DECLARE @CurrentModificationDate datetime;
	SET @CurrentModificationDate = (SELECT [Sys_DateOfModification] FROM [User] WHERE [UserKey] = @UserKey);
	If @ConcurrencyTimeStamp != @CurrentModificationDate
	BEGIN
		RAISERROR('Record is Changed by another process', 11,1);
	END
	
	DELETE FROM [UserProfile]
	WHERE 
		(
			[UserKey] = @UserKey
		)
 END
GO
